Skip to content

Support manual Megatron restarts with retained serving - #2444

Merged
zhuzilin merged 15 commits into
mainfrom
zilin/restart-megatron
Oct 7, 2026
Merged

zhuzilin merged 15 commits into
mainfrom
zilin/restart-megatron

Conversation

@zhuzilin

@zhuzilin zhuzilin commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Allow a failed Megatron training job to restart on the same Ray cluster while retaining healthy SGLang engines, routers, and accepted rollout data. The new trainer can change its parallel layout and replay the batches after the last committed checkpoint without regenerating samples or repeating accepted reward postprocessing.

Replay uses Straw storage (--rollout-data-transport straw) or per-rollout debug dumps (--save-debug-rollout-data with {rollout_id} in the path). Internal serving retention does not require the legacy --use-fault-tolerance flag.

The PR also makes recovery ownership explicit, publishes each converted training batch once, fixes restored disk-delta weight updates, and bounds cleanup independently of normal training and storage operations.

Changes

Serving and training lifetimes

  • Introduce a named, detached ServingCluster that owns routers, engines, placement groups, the queue controller, and the weight-update lock. RolloutManager borrows those resources and can be replaced independently.
  • Fence live training drivers before accepting a successor. Register trainer actors with serving so they can be released even after manager failure.
  • Retain serving and replay data after training failure; dispose the session after successful completion. Launchers preserve a running Ray cluster when resubmitting a job.
  • Let the driver own attempt cleanup, including rollback when startup fails after attaching to serving. Give an unresponsive manager a bounded opportunity to pause, then release trainers directly through serving. Cleanup failures do not replace the original training exception.
  • Dispose manager and serving resources independently, so a custom data source's cleanup error does not skip serving cleanup.

Checkpoint and replay ownership

  • Use queue receipts as the authority for accepted raw and converted batches. Represent conversion as an ordinary queue control task instead of maintaining a second batch-progress ledger.
  • Keep the recovery journal responsible for the committed model boundary and the replay window. Reconcile accepted queue results after manager death or a lost RPC reply.
  • Separate runtime training completion from durable checkpoint completion. Only a committed model/source checkpoint releases the associated replay pins.
  • Bound scheduler progress to buffered and currently collected work; discard finished conversion references instead of retaining an ever-growing delivery history.
  • Make checkpoint selection return a configuration copy and a restore plan. Pass checkpoint fields and the serving weight version through an explicit TrainingResume; keep long-lived data-source configuration separate from each trainer attempt.
  • Preserve the existing journal field representation and all public custom function signatures and return conventions.

Shared batch publication

  • Convert and publish the global training batch once. Send each DP rank a selection over shared tensor records instead of serializing another payload per rank.
  • Rebuild selections when training resumes with a different parallel layout. Keep R3/score-centering tensors lazy and reuse accepted converted data.
  • Keep custom conversion and reward-postprocessing hooks at the original whole-batch boundary.
  • Put asynchronous consumers on their owning data source, with its pause, restore, and close lifecycle, instead of using a module-global worker.

Engine recovery and weight synchronization

  • Bound engine reset and health-check RPCs, unregister failed engines, and terminate their serving children before replacing them.
  • Send old weight-update-group reset requests to all serving groups before waiting. Prefill and decode can share an NCCL group; waiting for one side before notifying the other can deadlock healthy PD engines.
  • On the first disk-delta update after trainer replacement or engine changes, publish the current restored weights as a full baseline. Keep weight versions above earlier publication attempts.
  • Restore the DDP gradient-synchronization hook correctly across repeated rollouts with overlap_grad_reduce.

Optimizer state and defaults

  • Support recovery with --use-stateless-adam --no-save-optim. Save and restore the LR/WD scheduler alongside the model; require RNG state and validate the scheduler sidecar before accepting the checkpoint.
  • Continue requiring optimizer state for ordinary Adam. Changes are confined to Slime's Megatron adapter; /root/Megatron-LM is unchanged.
  • Set both --rollout-health-check-timeout and --rollout-health-check-first-wait to 600 seconds by default.
  • Add an independent --rollout-cleanup-timeout, default 60 seconds, for exiting an attempt. It does not limit normal data reads, generation, training, or checkpoint writes.
  • Update English and Chinese recovery documentation and retain the CPU/GPU recovery suites in the CI matrix.

Validation

Regression and fault tests

Lifecycle/configuration validation recorded for commit 8a6406bd.

The lifecycle/configuration follow-up passed 443 distinct regression cases across training recovery, argument validation, Straw transport, fully asynchronous/distributed rollout, optional Straw dependencies, engine control, and score centering. Repeated verification runs are not added to this count.

The 12-case real-Ray manager recovery suite additionally covers:

  • Manager death after raw acceptance, conversion acceptance, or recovery-journal persistence.
  • Lost conversion replies with a surviving manager.
  • Replay and repartitioning with online GC both enabled and disabled.
  • Engine reset timeout while retaining healthy peers.
  • A live manager that cannot pause, and direct trainer release by the serving owner.
  • Joint prefill/decode reset through a barrier that requires both peers to participate.

Tests also check partial-startup rollback, cleanup error propagation, checkpoint selection without mutating requested paths, and unchanged args-based custom data-source construction.

Commands used for the final regression suites:

export PYTHONPATH="$PWD:$PWD/tests:/root/Megatron-LM"
OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 python -m pytest \
  tests/test_training_recovery.py \
  tests/test_megatron_argument_validation.py \
  tests/test_rollout_straw_transport.py \
  tests/test_server_control.py \
  tests/test_fully_async_rollout.py \
  tests/test_optional_straw.py \
  tests/test_score_centering.py \
  tests/test_distributed_rollout.py -q
python tests/test_rollout_manager_recovery.py

Existing test files remain registered in .github/workflows/pr-test.yml.j2; this follow-up adds cases to those files rather than new matrix entries.

GPU recovery

Validation used a four-host cluster with 8 H100 GPUs per host and shared JuiceFS storage.

The original recovery validation passed six GPU scenarios covering disk-delta updates, PD engine failure, object-store fully asynchronous rollout, ordinary Adam with overlapping gradient reduction, dense stateless Adam, and MoE stateless Adam with R3.

The lifecycle/configuration changes were also exercised with:

Scenario GPUs Fault and restart Checks
Qwen2.5-0.5B, PD, stateless Adam 4 Real training OOM, retained manager, TP 1 → 2 / DP 2 → 1 Healthy serving processes retained; checkpoint/scheduler restored; accepted samples replayed; subsequent training and saves complete
Qwen3-30B-A3B, R3, stateless Adam 8 Real training OOM plus manager loss, TP 1 → 2 / DP 4 → 2 Serving retained; samples and routing data replayed; scheduler progress restored; finite gradients and completed training

Large-MoE recovery uses stateless Adam; ordinary Adam recovery is covered by the dense-model scenarios.

Batch-publication measurement

Measured Qwen3-30B-A3B on 32 H100s: 16 training GPUs, 16 serving GPUs, configured serving concurrency 256, 256 samples per rollout, 1,024 generated tokens per sample, four rollouts, and R3 enabled. TP=2, EP=8, DP=8.

Manager phase Before Shared-batch publication
Whole-batch conversion 0.00699 s 0.00641 s
Global publication Not timed separately 1.92476 s
DP partition/publication 3.09694 s 0.09642 s

These are phase means. The DP phase becomes about 32.1× faster because it builds selections over one published batch. This is not an end-to-end throughput speedup; the revised global-publication cost is reported separately. R3 routes were nonempty and fully consumed during the measured training runs.

Scope and limitations

  • Recovery requires resubmitting the job to the same live Ray cluster. This PR does not introduce automatic job retries.
  • Losing the serving owner or the whole Ray cluster requires cold startup from a committed checkpoint.
  • Keep model, rollout settings, global batch size, session identity, and custom hook configuration unchanged when attaching to retained serving. Supported trainer parallelism and memory settings can change.
  • Stateless Adam rebuilds FP32 master parameters from the saved model precision. Parallel-layout changes can also alter RNG behavior; bitwise-identical training after restart is not promised.

Give internal serving a detached owner for engines, routers, GPU placements
and the Straw controller. Use the same startup path with health checks on
or off, persist Megatron replay state for Straw/debug transport, and rebuild
failed managers against retained serving. Preserve external deployment and
custom hook contracts.

Cover manager death, driver fencing, source progress, checkpoint handoff and
batch replay across changed trainer parallelism. Register all three manager
restart scenarios in the generated GPU CI matrix.

Validation: 291 CPU cases and three four-H100 restart e2e scenarios passed.
Re-ran the 35 recovery and 75 transport cases after final cleanup; all
pre-commit hooks and e2e artifact assertions passed.
Always monitor internal serving and force health checks at rollout boundaries.
Remove dead router workers independently of their engine actors before abort
or offload, then recover missing engines before the next weight update.

Keep the external-serving policy and compatibility flag, use a 600-second
background interval, and bound health/shutdown HTTP and Ray waits.

Add CI e2e coverage for stale registrations after HTTP server and Ray actor
crashes. Validated with 251 CPU tests, both 4-H100 crash e2e cases, a
3-engine PipelineRL continuity regression, and all pre-commit checks.
Keep topology and health monitoring in ServingCluster. Use engine snapshots
for rollout memory controls, make finish_rollout explicit, remove duplicate
monitoring and control forwarding, and include the update lock in startup.
Document session lookup, resource ownership and the critical control ordering.

Journal accepted batches and their source cursor together. Recover only
missing engines so reusing a live manager preserves the replacement trainer's
connection markers. Register the retained-manager restart scenario in CI.

Validation: 348 CPU regressions, 253 final core regressions, all pre-commit
checks, and seven H100 e2e scenarios covering manager replacement/reuse,
server/actor crashes, PipelineRL continuity and mixed-model offload/recovery.
@zhuzilin
zhuzilin force-pushed the zilin/restart-megatron branch from 6a0fb01 to 5f8faf0 Compare October 6, 2026 05:03
A manager can die after Straw accepts a collection but before the training recovery journal records it. Reconcile that accepted receipt before recovering the old readers so replay preserves the original selection instead of conflicting with the completed collection.

Add two-node Ray SIGKILL coverage for raw acceptance and converted batches, with online GC enabled and disabled, and verify repartitioning from DP=1 to DP=2. Cover restart before initial model loading, update checkpoint tests for the train entry point, and register the new test in CI.

Validation: 4 new process-recovery e2e cases and 167 related regression tests passed. The existing 4-GPU Qwen2.5-0.5B recovery e2e also passed with a real OOM at rollout 1, manager death during training, TP=1 to TP=2, DP=2 to DP=1, two replayed batches, and retained SGLang engines. Black, isort and git diff --check passed.
Bound engine reattachment and retire stalled peers, preserve disk-delta
baselines across trainer restarts, and freeze retained rollout inputs.
Use queue receipts as the acceptance authority, keep only the checkpoint
replay window, and share one converted batch through DP index views.
Move async worker ownership to the data source without changing custom hooks.

Support stateless Adam recovery without optimizer tensors by committing its
scheduler with the model. Keep ordinary Adam optimizer/RNG requirements and
reuse DDP callbacks across rollouts. No changes to the Megatron-LM dependency.

Validation: 419 CPU regression cases, 11 Ray fault cases, and 6 GPU recovery
scenarios including disk-delta, PD with a stalled engine, and MoE/R3.
A Qwen3-30B-A3B benchmark on 32 H100 GPUs with 256 configured concurrency
reduced the DP phase from 3.10 s to 0.096 s; global publication takes 1.92 s.
These phase measurements do not imply an end-to-end training speedup.
Keep attempt teardown with the driver and release serving resources despite manager failures. Preserve requested configuration through explicit checkpoint and resume handoffs. Reset all PD weight-update peers before waiting, and separate cleanup deadlines from the 600-second health defaults.
@zhuzilin
zhuzilin merged commit 4a7a509 into main Oct 7, 2026
208 of 211 checks passed
@zhuzilin
zhuzilin deleted the zilin/restart-megatron branch October 7, 2026 01:46
mzopedia added a commit to mzopedia/slime that referenced this pull request Oct 8, 2026
Evaluation runs on the source-owned worker that THUDM#2444 introduced; a
distributed worker still rejects evaluation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant